<?
require_once("ericdingle/php/AuthViewController.php");
require_once("ericdingle/model/photo/PhotoProvider.php");

class EditAlbum extends AuthViewController {
	public function doGet($postID = NULL) {
		if (!$postID) {
			$postID = $_GET["postID"];
			if (!$postID) {
				header("Location: viewPosts");
				exit();
			}
		}
		
		// check if this post has an album
		$photoProvider = PhotoProvider::getInstance();
		$photos = $photoProvider->readByPostID($postID);
		
		if (count($photos) == 0) {
			$root = $_SERVER["DOCUMENT_ROOT"];
			$files = scandir("$root/ericdingle/data/img");
			
			$folders = array();
			foreach ($files as $file) {
				if ($file[0] != "." && is_dir("$root/ericdingle/data/img/$file")) {
					array_push($folders, $file);
				}
			}
			$folders = array_reverse($folders);
		}
		
		// load the views
		require_once("ericdingle/php/Tabs.php");
		$this->loadView("ericdingle/view/header.php", array(
			"isLoggedIn" => true,
			"tabID" => TabID::BLOG,
			"tabs" => $tabs
		));
		$this->loadView("ericdingle/view/editAlbum.php", array(
			"postID" => $postID,
			"folders" => $folders,
			"photos" => $photos
		));
		$this->loadView("ericdingle/view/footer.php");
	}
	
	public function doPost() {
		$postID = $_POST["postID"];
		$photoProvider = PhotoProvider::getInstance();
		
		if ($_POST["generate"]) {
			$root = $_SERVER["DOCUMENT_ROOT"];
			$folder = stripslashes($_POST["folder"]);
			$files = scandir("$root/ericdingle/data/img/$folder");
			foreach ($files as $file) {
				if (substr($file, -3) == "jpg") {
					$photo = new PhotoEntity(
						null,
						$postID,
						str_replace(" ", "%20", "data/img/$folder/$file"),
						null
					);
					
					$photoProvider->create($photo);
				}
			}
		} else if ($_POST["save"]) {
			$captions = $_POST["captions"];
			foreach ($captions as $photoID => $caption) {
				$photo = new PhotoEntity(
					$photoID,
					null,
					null,
					stripslashes($caption)
				);
				
				$photoProvider->update($photo);
			}
			
			header("Location: viewPosts");
			exit();
		} else if ($_POST["delete"]) {
			$photoProvider->deleteByPostID($postID);
		}
		
		$this->doGet($postID);
	}
}
?>
